package cn.yoline.xylink.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ainemo.sdk.otf.ConnectNemoCallback;
import com.ainemo.sdk.otf.LoginResponseData;
import com.ainemo.sdk.otf.MakeCallResponse;
import com.ainemo.sdk.otf.NemoSDK;
import com.ainemo.sdk.otf.VideoConfig;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import cn.yoline.xylink.R;
import cn.yoline.xylink.XylinkStore;
import cn.yoline.xylink.constant.MeetingConstant;
import cn.yoline.xylink.utils.MeetingSoundUtil;
import cn.yoline.xylink.widget.ProgressDialog;
import io.reactivex.observers.DisposableObserver;

/**
 * Copyright 2020 JxGIS
 *
 * @file IncomingCallActivity
 * @auth linaisheng
 * Created on 2022/7/27.
 * Description：
 */
public class IncomingCallActivity extends BaseActivity {

    private MeetingSoundUtil mediaSoundUtil;
    private Vibrator vibrator;

    private String mCallNumber;
    private String mCallUserName;
    private String numberPwd;
    private String meetingRoomName;

    private String userName;
    private String userId;
    private boolean isLoginSuccess;

    private XylinkStore xylinkStore = XylinkStore.getInstant();

    private TextView tvIncomingNumber;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.activity_meeting_incoming_call);

        xylinkStore.setIsOnMeeting(true);
        tvIncomingNumber = findViewById(R.id.incoming_number);
        findViewById(R.id.incoming_hangup).setOnClickListener(view -> {
            xylinkStore.setIsOnMeeting(false);
            finish();
        });

        mediaSoundUtil = MeetingSoundUtil.getInstance(this);
        mediaSoundUtil.playIncomingCallSound();

        vibrator = (Vibrator)this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(new long[]{1000, 1000, 1000, 1000}, 0);

        findViewById(R.id.incoming_accept).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaSoundUtil.stopPlay();
                vibrator.cancel();
                checkPermission();
            }
        });

        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        mCallNumber = intent.getStringExtra(MeetingConstant.CALL_NUMBER);
        mCallUserName = intent.getStringExtra(MeetingConstant.CALL_USER_NAME);
        numberPwd = intent.getStringExtra(MeetingConstant.CALL_NUMBER_PWD);

        meetingRoomName = intent.getStringExtra(MeetingConstant.MEETING_ROOM_NAME);

        if (intent.hasExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG)) {
            String videoConfig = intent.getStringExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG);
            if (VideoConfig.VD_320x180.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_320x180);
            } else if (VideoConfig.VD_640x360.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_640x360);
            } else if (VideoConfig.VD_1280x720.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_1280x720);
            } else {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_1280x720);
            }
        }


        userId = intent.getStringExtra(MeetingConstant.USER_ID);
        userName = intent.getStringExtra(MeetingConstant.USER_NAME);

        if (isEmpty(mCallNumber)) {
            showToast("号码为空");
            finish();
            return;
        } else if (isEmpty(userId)) {
            showToast("用户id为空");
            finish();
            return;
        }  else if (isEmpty(userName)) {
            showToast("用户名为空");
            finish();
            return;
        }
        if (!TextUtils.isEmpty(mCallUserName)) {
            tvIncomingNumber.setText(mCallUserName);
        } else if (!TextUtils.isEmpty(meetingRoomName)) {
            tvIncomingNumber.setText(meetingRoomName);
        } else {
            tvIncomingNumber.setText(mCallNumber);
        }

        //预登录
        NemoSDK nemoSDK = NemoSDK.getInstance();
        nemoSDK.loginExternalAccount(userName, userId, new ConnectNemoCallback() {

            @Override
            public void onFailed(String code) {

            }

            @Override
            public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                XylinkStore.getInstant().setTokenInfo(loginResponseData.getTokenInfo());
                isLoginSuccess = true;
            }

            @Override
            public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

            }
        });
    }


    private void loginXylink() {
        NemoSDK.getInstance().loginExternalAccount(
                userName, userId, new ConnectNemoCallback() {

            @Override
            public void onFailed(String code) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("会议登录失败，请重试");
                        jointMeeting();
                    }
                });

            }

            @Override
            public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                XylinkStore.getInstant().setTokenInfo(loginResponseData.getTokenInfo());
                isLoginSuccess = true;
            }

            @Override
            public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

            }
        });
    }


    private boolean[] isPermissionGranted;
    @SuppressLint("CheckResult")
    private void checkPermission() {
        isPermissionGranted = new boolean[]{ false, false };
        RxPermissions permissions = new RxPermissions(this);
        permissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                .compose(bindToLifecycle())
                .subscribe(new DisposableObserver<Permission>() {
                    @Override
                    public void onNext(Permission permission) {
                        if (permission.name.equals(Manifest.permission.CAMERA)) {
                            //CAMERA 权限获取成功时，permission.granted=true
                            isPermissionGranted[0] = permission.granted;
                        } else if (permission.name.equals(Manifest.permission.RECORD_AUDIO)) {
                            //当RECORD_AUDIO 权限获取成功时，permission.granted=true
                            isPermissionGranted[1] = permission.granted;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("授权失败");
                    }

                    @Override
                    public void onComplete() {
                        if (!isPermissionGranted[0]) {
                            showToast("未授权“相机”权限");
                        } else if (!isPermissionGranted[1]) {
                            showToast("未授权“录音”权限");
                        } else {
                            if (isLoginSuccess) {
                                jointMeeting();
                            } else {
                                loginXylink();
                            }
                        }
                    }
                });
    }

    private void jointMeeting() {
        progressDialog = new ProgressDialog(IncomingCallActivity.this, "加入会议中");
        progressDialog.show();
        NemoSDK.getInstance().makeCall(mCallNumber,
                !isEmpty(numberPwd) ? numberPwd : "",
                new MakeCallResponse() {
                    @Override
                    public void onCallSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 查询号码成功, 进入通话界面
                                progressDialog.dismiss();
                                xylinkStore.setIsOnMeeting(true);
                                startActivity(MeetingRoomActivity.getStartIntent(
                                        IncomingCallActivity.this,
                                        mCallNumber, meetingRoomName));
                                finish();
                            }
                        });
                    }

                    @Override
                    public void onCallFail(String error, String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.dismiss();
                                showToast("加入会议失败：" + error);
                            }
                        });
                    }
                });
    }

    @SuppressLint("InvalidWakeLockTag")
    public static void wakeUpAndUnlock(Context context){
        //屏锁管理器
        KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        //解锁
        kl.disableKeyguard();
        //获取电源管理器对象
        PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
        //点亮屏幕
        wl.acquire();
        //释放
        wl.release();
    }

    @Override
    public void onBackPressed() {
        xylinkStore.setIsOnMeeting(false);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaSoundUtil.stopPlay();
        vibrator.cancel();
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private boolean isEmpty(final CharSequence s) {
        return s == null || s.length() == 0;
    }

    public static Intent getStartIntent(
            Context context, String callNumber, String numberPwd,
            String userId, String userName) {
        Intent intent = new Intent(context, IncomingCallActivity.class);
        intent.putExtra(MeetingConstant.CALL_NUMBER, callNumber);
        intent.putExtra(MeetingConstant.CALL_NUMBER_PWD, numberPwd);

        intent.putExtra(MeetingConstant.USER_ID, userId);
        intent.putExtra(MeetingConstant.USER_NAME, userName);
        return intent;
    }


    public static Intent getStartIntent(
            Context context, String callNumber, String numberPwd,
            String userId, String userName, String videoConfig) {
        Intent intent = new Intent(context, IncomingCallActivity.class);
        intent.putExtra(MeetingConstant.CALL_NUMBER, callNumber);
        intent.putExtra(MeetingConstant.CALL_NUMBER_PWD, numberPwd);

        intent.putExtra(MeetingConstant.USER_ID, userId);
        intent.putExtra(MeetingConstant.USER_NAME, userName);
        intent.putExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG, videoConfig);
        return intent;
    }


}